// pages/newIndex/newIndex.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    iswifi:false,
    login: false,
    phone:false,
    loginShow: false,
    req: false,
    active: 1,
    searchClear: false,
    pageEnd: false,
    param: {
      pageNumber: 1,
      pageSize: 10
    },
    list: [],
    remind: [],
    show: false,
    typeShow: false,
    refresh:"1",
    numbers:{},
    banners:[],
    recommends:[],
    sendAct:false,
    check:false,
  },
  login() {
    if(this.data.login){
      this.toggle('phoneshow', true)
      this.selectComponent('#phone').showClose()
    }else{
      this.toggle('loginShow', true)
      this.selectComponent('#login').showClose()
    }
  },
  // loginClose() {
  //   this.toggle('loginShow', false)
  // },
  toggleToast(e) {
    // console.log(e.detail)
    if (!e.detail.loginShow) {
      this.toggle('loginShow', false)
    }
    this.onShow()
  },
  toggleToast1(e) {
    // console.log(e.detail)
    if (!e.detail.phoneshow) {
      this.toggle('phoneshow', false)
    }
    this.onShow()
  },
  sendAct(){
    this.toggle('sendAct', true)
  },
  check: function (e) {
    this.toggle("check", true);
    this.toggle("typeShow", false)
  },
  torelease(){
    var that = this
    if(that.data.orglist.length==1){
      wx.navigateTo({
        url: '/pages/orgRelease/orgRelease?id=' + that.data.orglist[0].id + "&orgSearch=" + that.data.orglist[0].orgSearch,
      })
    }else{
      wx.navigateTo({
        url: '/pages/recommendOrg/recommendOrg?isindex=1',
      })
    }
  },
  getorglist(){
    var that = this
    app.req({
      url: "orgmini/home/getOrg",
      data: {
       type:5
      },
      success: function (res) {
        if (200 == res.code) {
          that.toggle("orglist", res.data);
        }
      }
    });
  },
  user(e) {
    var that = this;
    app.getRefresh(function (refresh) {
    },'0')
    var id = e.currentTarget.dataset.createuid;
    var name = e.currentTarget.dataset.name;
    wx.navigateTo({
      url: '/pages/myCardNew/myCardNew?type=visitor&id=' + id + '&name=' + name,
    })
  },
  org(e) {
    var that = this;
    app.getRefresh(function (refresh) {
    }, "0")
    var dataset = e.currentTarget.dataset;
    wx.navigateTo({
      url: '/pages/orgHome/orgHome?id=' + dataset.orgid
    })
  },
  showType() {
    getApp().mtj.trackEvent('yqlw_act_create');
    this.toggle("typeShow", true)
  },
  typeClose() {
    this.toggle("typeShow", false)
    this.toggle("wishShow", false)
    this.toggle('sendAct', false)
  },

  mini: function(e) {
    var that = this;
    var d = e.currentTarget.dataset;
    if (d.type == 13){
      this.toggle("typeShow", false)
      this.toggle("wishShow", true)
      return
    }
    if(d.type==4){
      getApp().mtj.trackEvent('yqlw_act_banquet');
    } else if (d.type == 3){
      getApp().mtj.trackEvent('yqlw_act_sports');
    } else if (d.type == 8) {
      getApp().mtj.trackEvent('yqlw_act_meeting');
    } else if (d.type == 12) {
      getApp().mtj.trackEvent('yqlw_act_birth');
    } else if (d.type == 14) {
      getApp().mtj.trackEvent('yqlw_act_hundred');
    } else if (d.type == 15) {
      getApp().mtj.trackEvent('yqlw_act_banquet');
    }
    var url = "";
    if(d.turn){
      url = d.turn
    }else{
      url = d.type == 12 ? 'pages/sport/sport' : 'pages/party/party';
    }
    url += "?type=" + d.type + "&name=" + d.name;
    // console.log("组织url", url)

    wx.navigateToMiniProgram({
      appId: !Boolean(d.turn) ? app.globalData.activityMiniAppId : app.globalData.blessingMiniAppId,
      envVersion: !Boolean(d.turn) ? app.globalData.activityMiniEnvVersion : app.globalData.blessingMiniEnvVersion,
      path: url,
      success(res) {
        that.toggle("typeShow", false);
      }
    })
  },
  onChange(e) {
    var that = this
    if (e.detail.index != that.data.active) {
      that.toggle('active', e.detail.index)
      that.toggle('param.pageNumber', 1)
      that.toggle('pageEnd', false)
      that.toggle('list', [])
      that.list()
    }
  },
  searchIpt(e) {
    var that = this
    that.toggle('searchContent', e.detail.value)
    if (e.detail.value) {
      that.toggle('searchClear', true)
    }
  },
  searchClear() {
    var that = this
    that.toggle('searchContent', '')
    that.toggle('searchClear', false)
  },
  remind: function() {
    var that = this;
    app.req({
      url: "orgmini/home/schedule",
      data: {
        pageNumber: 1,
        pageSize: 2
      },
      success: function(res) {
        if (200 == res.code) {
          var remind = res.data.rows
          for (var item of remind) {
            item.actTime = item.actStartTime.substring(5, 7) + '月' + item.actStartTime.substring(8, 10) + '日'
          }
          that.toggle("remind", remind);
        }
      }
    });
  },
  cancelAttention(e) {
    var that = this
    var orgid = e.currentTarget.dataset.orgid
    app.req({
      url: "orgmini/attention/cancelAttention",
      data: {
        orgId: orgid
      },
      success: function (res) {
        if (200 == res.code) {
          wx.showToast({
            title: '成功取消关注',
            duration: 3000,
            icon:'none'
          })
          that.list()
        }
      }
    });
  },
  toaddorg(e){
    var dataset = e.currentTarget.dataset;
    if (dataset.type==0){
      wx.showToast({
        title: '您已提交加入申请，请耐心等待组织管理员审核',
        icon:'none'
      })
    }else{
      wx.navigateTo({
        url: '/pages/joinOrg/joinOrg?orgId=' + dataset.orgid
      })
    }
  },
  list: function(append) {
    var that = this;
    that.toggle('req', false)
    if (that.data.active == 1) {
      var url ="orgmini/home/allList"
    } else if (that.data.active == 2) {
      var url ="orgmini/home/homeRecommendList"
    }
    var param = that.data.param
    app.req({
      url: url,
      data: param,
      success: function(res) {
        if (200 == res.code) {
          if (res.data) {
            var list = res.data.rows
          } else {
            var list = []
          }
          if(list.length>0){
          var arr = []
          arr = list.filter(function (item) {
            return item.type == 5 || item.type == 6;
          });
          list.push(arr)
          }
          var birthList=[];
          var lock = false;
          for (var item of list) {
            if (item.createTime){
              var timestamp = Date.parse(new Date());
              var date = new Date(timestamp);
              item.createTime = item.createTime.substring(5, 7) + '月' + item.createTime.substring(8, 10) + '日 ' + item.createTime.substring(11, 16)
            }
            item.lock = 0;
            if (item.type == 0) {
              if (item.actStartTime.substring(0, 10) == item.actEndTime.substring(0, 10)) {
                item.actTime = item.actStartTime.substring(5, 7) + '月' + item.actStartTime.substring(8, 10) + '日' + item.actStartTime.substring(11, 16) + '-' + item.actEndTime.substring(11, 16)
              } else {
                item.actTime = item.actStartTime.substring(5, 7) + '月' + item.actStartTime.substring(8, 10) + '日' + item.actStartTime.substring(11, 16) + '-' + item.actEndTime.substring(5, 7) + '月' + item.actEndTime.substring(8, 10) + '日' + item.actEndTime.substring(11, 16)
              }
            }
            if (item.type == 7){
              birthList.push({
                friendName: item.friendName,
                friendUrl: item.friendUrl,
                orgName: item.orgName
              })
            }
            if (item.type == 7 && !lock){
              item.lock = 1;
              lock = true;
              item.birthList = birthList;
            }
            if(item.poster && (item.poster.indexOf('?imageView2/1/q/30/format/jpg/ignore-error/1')!= -1 || item.poster.indexOf('?imageView2/1/format/jpg/q/80/ignore-error/1')!= -1  )){
              item.poster = item.poster.split('?imageView2/1/q/30/format/jpg/ignore-error/1')[0];
              item.poster = item.poster.split('?imageView2/1/format/jpg/q/80/ignore-error/1')[0];
            }
          }
          that.toggle('birthList', birthList)
          if (!list || list.length < param.pageSize) {
            that.toggle("pageEnd", true);
          }
          // console.log('列表',list)
          that.toggle("list", append ? that.data.list.concat(list) : list);
          that.toggle('req', true)
        }
      }
    });
  },

  gethomedata(){
    var that = this
    app.req({
      url: "orgmini/home/homeData",
      success: function (res) {
        if (200 == res.code) {
        //  console.log('未读数',res.data)
         that.toggle('numbers',res.data)
        }
      }
    });
  },
  activityDetail: function(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    wx.navigateToMiniProgram({
      appId: app.globalData.activityMiniAppId,
      envVersion: app.globalData.activityMiniEnvVersion,
      path: 'pages/register/register?id=' + id,
      success(res) {
        // console.log(res);
      }
    })
  },
  toggle(type, val) {
    this.setData({
      [type]: val
    });
  },
  toPage(e) {
    var that = this;
    app.getRefresh(function (refresh) {
    }, '0')
    var dataset = e.currentTarget.dataset;
    var url = dataset.turn
    if (url =='/packageA/pages/schedule/schedule'){
      getApp().mtj.trackEvent('yqlw_home_remind');
    } else if (url =='/packageA/pages/searchRes/searchRes') {
      getApp().mtj.trackEvent('yqlw_home_search');
    }else{
      getApp().mtj.trackEvent('yqlw_home_recommend');
    }
    if (dataset.id) {
      url = url + '?id=' + dataset.id
    }
    if (dataset.orgid) {
      url = url + '&orgId=' + dataset.orgid
    }
    if (dataset.type) {
      url = url + '&type=' + dataset.type
    }
    // console.log(url)
    wx.navigateTo({
      url: url
    })
  },
  toPage1(e){
    var dataset = e.currentTarget.dataset;
    var url = dataset.turn
    var type = dataset.type
    if(type==3){
      wx.navigateToMiniProgram({
        appId: app.globalData.activityMiniAppId,
        envVersion: app.globalData.activityMiniEnvVersion,
        path: 'pages/register/register?id=' + dataset.id,
        success(res) {
          // console.log(res);
        }
      })
    }else{
      if (dataset.id) {
        url = url + '?id=' + dataset.id
      }
      if (dataset.orgid) {
        url = url + '&orgId=' + dataset.orgid
      }
      if (dataset.type) {
        url = url + '&type=' + dataset.type
      }
      wx.navigateTo({
        url: url
      })
    }
  },
  tomessage(e){
    var type= e.currentTarget.dataset.type
    if(type==1){
      app.searchWord = 'val';
    }else{
      app.searchWord = 'val1';
    }
    wx.switchTab({
      url:'/pages/message/message'
    })
  },
  tobirthday(e) {
    var dataset = e.currentTarget.dataset;
    var limit = dataset.limit ? "true" :"false";
    // console.log('/pages/birthday/birthday?id=' + dataset.id + "&limit=" + limit)
    wx.navigateTo({
      url: '/pages/birthday/birthday?id=' + dataset.id + "&limit=" + limit
    })
    var that = this;
    app.getRefresh(function (refresh) {
    }, '0')
  },
  getbanner(){
    var that = this
    app.req({
      url: "orgmini/home/getBanner",
      data:{
        platform:1
      },
      success: function (res) {
        if (200 == res.code) {
          that.toggle('banners', res.data.banners)
          that.toggle('recommends', res.data.recommends)
        }
      }
    });
  },
  bannerbtn(e){
    var that = this
    var id = e.currentTarget.dataset.id
    var type = e.currentTarget.dataset.type
    if(type==0){
      wx.navigateToMiniProgram({
        appId: app.globalData.activityMiniAppId,
        envVersion: app.globalData.activityMiniEnvVersion,
        path: 'pages/register/register?id=' + id,
        success(res) {
          // console.log(res);
        }
      })
    }else if(type==5){
      wx.navigateTo({
        url: '/pages/orgHome/orgHome?id=' + id
      })
    }else{
      wx.navigateTo({
        url: '/pages/contentDetails/contentDetails?id=' + id
      })
    }
  },
  openIsOrg(e){
    var index = e.currentTarget.dataset.index;
    var isFriend = e.currentTarget.dataset.isfriend;
    var orgacttype = e.currentTarget.dataset.orgacttype
    // console.log(index);
    // if (isFriend == 0 && orgacttype==1){
    //   wx.showToast({
    //     title: '您已申请添加对方好友，对方正在审核中',
    //     icon:"none"
    //   })
    // }else{
      var temp_str = 'list[' + index + '].isOrg';
      this.setData({
        [temp_str]:true
      })
    // }
  },
  bannerbtn2(){
    wx.navigateTo({
      url: '/pages/statistics/statistics?isorg=0',
    })
  },
  // 加好友
  addFriend(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var temp_str = 'list[' + index + '].isOrg';
    var id = e.currentTarget.dataset.id;
    var isFriend = e.currentTarget.dataset.isfriend;
    var orgacttype = e.currentTarget.dataset.orgacttype
    // console.log(e, orgacttype, isFriend);
    if (isFriend == 0 && orgacttype == '1') {
      wx.showToast({
        title: '您已申请添加对方好友，对方正在审核中',
        icon: "none"
      })
      this.setData({
        [temp_str]: false
      })
    }else{
    app.req({
      url: 'orgmini/FriendVisitor/applyFriend',
      data: {
        friendId: id,
      },
      success: function (res) {
        if (200 == res.code) {
          that.setData({
            [temp_str]: false
          })
          that.list();
          wx.showToast({
            title: '已发送申请',
            duration: 2000
          })
        }
      }
    });
    }
  },
  preventTouchMove: function (e) {
  },
  isorghide(e){
    var index = e.currentTarget.dataset.index;
    var temp_str = 'list[' + index + '].isOrg';
    this.setData({
      [temp_str]: false
    })
  },
  refresh(){
    var that = this
    that.onLoad()
    that.onShow()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this
    that.getbanner()
    wx.getNetworkType({
      success(res) {
        const networkType = res.networkType
        console.log('网络', networkType)
        if (networkType=='none'){
          that.toggle('iswifi', true)
        }else{
          that.toggle('iswifi', false)
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  getTotalUnRead: function () {
    var that = this;
    app.req({
      url: "orgmini/notice/newReadCount",
      success: function (res) {
        if (200 == res.code) {
          if (res.data.sysMessageCount > 0 || res.data.applyMessageCount > 0) {
            wx.showTabBarRedDot({
              index: 2
            })
          } else {
            wx.hideTabBarRedDot({
              index: 2,
            })
          }
        }
      }
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this
    app.getRefresh(function (refresh) {
      // console.log('我是全局refresh', refresh)
      that.toggle('refresh', refresh)
    })
    // console.log('最终refresh', this.data.refresh)
    that.toggle('sendAct', false)
    that.toggle('typeShow', false)
    if (that.data.refresh == '1') {
      // console.log('我刷新了', that.data.refresh)
      wx.getSetting({
        success(res) {
          // if (!res.authSetting['scope.userInfo'] || wx.getStorageSync('uid') == '') {
          if (wx.getStorageSync('uid') == '') {
            that.toggle("login", false);
            that.toggle("active", 1);
            //  that.list();
          } else {
            that.toggle("login", true);
            var phone = wx.getStorageSync("phone")
            if(phone == ''){
              that.toggle("phone", true);
            }else{
              that.toggle("phone", false);
              that.toggle("phoneshow", false);
              that.toggle("loginShow", false);
              //  console.log('隐藏',that.data.phoneshow)
            app.getUserInfo(function (userInfo) {
              that.toggle("uid", userInfo.id);
              if (userInfo.userOrgList.length) {
                that.toggle("active", 1);
                that.list();
                that.remind()
                that.getTotalUnRead()
                that.gethomedata() 
                that.getorglist()    
              } else {
                that.toggle("active", 1);
                that.list();
                that.remind()
                that.getTotalUnRead()
                that.gethomedata()
                that.getorglist()  
              }
            })
            }
          }
        },
      })
   }
    wx.setNavigationBarTitle({
      title: '首页',
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    var that = this;
    if (wx.getStorageSync("phone") !=''){
      that.toggle("param.pageNumber", 1);
      that.toggle("pageEnd", false);
      that.list();
      that.gethomedata()
      that.getbanner()
    }else{
      wx.stopPullDownRefresh() 
      that.list();
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var that = this;
    if (!that.data.pageEnd) {
      that.toggle("param.pageNumber", that.data.param.pageNumber + 1);
      that.list(true);
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})